<template>
  <div class="fourJiao all-height-width" id="eightJiaoBox">
    <!-- 基础图片层（唯一） -->
    <div id="circleCenter" class="fourJiao4 all-height-width">
      <img :src="pegSrc" height="100%" width="100%" alt="视频流未播放" v-if="props.imgFlag"/>
    </div>

    <!-- 左右布局容器 -->
    <div  class="circleLayersContainer all-height-width">
      <!-- 左侧切圆信息 -->
      <div class="circleLayer">
        <div class="fourJiao1 event-none"></div>
        <canvas v-show="props.isShowChecked" id="circle1" ref="canvasEl1" class="fourJiao2 all-height-width"></canvas>
        <div class="fourJiao3 all-height-width event-none">
          <span style="color: red">+</span>
        </div>
        <!-- <span :style="`left:${cx1}px; top:${cy1}px;`" class="clCenter">+</span> -->
      </div>

      <!-- 右侧切圆信息 -->
      <div class="circleLayer">
        <div class="fourJiao1 event-none"></div>
        <canvas v-show="props.isShowChecked" id="circle2" ref="canvasEl2" class="fourJiao2 all-height-width"></canvas>
        <div class="fourJiao3 all-height-width event-none">
          <span style="color: red">+</span>
        </div>
        <!-- <span :style="`left:${cx2}px; top:${cy2}px;`" class="clCenter">+</span> -->
      </div>
    </div>
  </div>
</template>

<script setup>
import { onMounted, ref, nextTick, defineProps,onUnmounted } from "vue";
import { useRoute } from "vue-router";
const route = useRoute();
let jiaowidth = ref(0);
let jiaoheight = ref(0);

let canvasEl1 = ref(); // 左侧canvas引用
let canvasEl2 = ref(); // 右侧canvas引用

const props = defineProps({
  isShowChecked: true,
  cx: 0,
  cy: 0,
  rx: 0,
  ry: 0,
  cx2: 0,
  cy2: 0,
  rx2: 0,
  ry2: 0,
  scaling_ratio:1,
  imgFlag: false
});

watch(
  () => props.cx,
  (val) => {
    if (val) {
      const ctx = canvasEl1.value.getContext("2d");
      clearCanvas(canvasEl1.value,ctx);

      const ctx2 = canvasEl2.value.getContext("2d");
      clearCanvas(canvasEl2.value,ctx2);

      let originalCenter = {
        x: 960,
        y: 540,
      };

      let newCenter = {
        x: jiaowidth.value / 2,
        y: jiaoheight.value / 2,
      };

      let n = newCenter.x / originalCenter.x;

      let points = getPointsByScreen(
        newCenter,
        originalCenter,
        {
          x: props.cx,
          y: props.cy,
        },
        n
      );

      // 设置椭圆的样式
      ctx.lineWidth = 2;
      ctx.strokeStyle = "#6AFFB2";
      ctx.beginPath();
      ctx.ellipse(
        points.x,
        points.y,
        (props.rx / 2 * n)  * props.scaling_ratio,
        (props.ry / 2  * n)  * props.scaling_ratio,
        0,
        0,
        Math.PI * 2
      );
      ctx.fillStyle = "#6AFFB2";
      // 绘制垂直线条
      ctx.fillRect(
        points.x, // x 坐标
        points.y - 4, // y 坐标
        2, // 宽度
        10 // 高度
      );

      // 绘制水平线条
      ctx.fillRect(
        points.x - 4, // x 坐标
        points.y, // y 坐标
        10, // 宽度
        2 // 高度
      );
      ctx.stroke(); // 描边


      
      let points2 = getPointsByScreen(
        newCenter,
        originalCenter,
        {
          x: props.cx2,
          y: props.cy2,
        },
        n
      );
      // 设置椭圆的样式
      ctx2.lineWidth = 2;
      ctx2.strokeStyle = "#6AFFB2";
      ctx2.beginPath();
      ctx2.ellipse(
        points2.x,
        points2.y,
        (props.rx2 / 2 * n)  * props.scaling_ratio,
        (props.ry2 / 2  * n)  * props.scaling_ratio,
        0,
        0,
        Math.PI * 2
      );
      ctx2.fillStyle = "#6AFFB2";
      // 绘制垂直线条
      ctx2.fillRect(
        points2.x, // x 坐标
        points2.y - 4, // y 坐标
        2, // 宽度
        10 // 高度
      );

      // 绘制水平线条
      ctx2.fillRect(
        points2.x - 4, // x 坐标
        points2.y, // y 坐标
        10, // 宽度
        2 // 高度
      );
      ctx2.stroke(); // 描边

    }
  },
  { deep: true, immediate: true }
);

function clearCanvas(canvasObj,ctx) {
  if (canvasObj) {
    // if(!ctx){
    //    let ctx = canvasEl.value.getContext("2d");
    // }
    ctx.clearRect(0, 0, canvasObj.width, canvasObj.height);
  }
}

function getPointsByScreen(newCenter, originalCenter, points, n) {
  let newX = newCenter.x + (points.x - originalCenter.x) * n;
  let newY = newCenter.y + (points.y - originalCenter.y) * n;

  return {
    x: newX,
    y: newY,
  };
}

const canvasSize = ref({ width: 0, height: 0 });
const pegSrc = ref(
  import.meta.env.VITE_APP_BASE_API + `api/video/stream.mjpeg?timestamp=${Date.now()}`
);

onMounted(() => {
  setTimeout( () => {
    nextTick(() => {
      setC();
    });
  }, 1000)
});

function _setC() {
  // 左侧切圆参数
  let options1 = {
    width: 13335,
    height: 12829,
    x: 300,
    y: 0,
    rx: 9601,
    ry: 9034,
  };

  // 右侧切圆参数（可独立调整）
  let options2 = {
    width: 12000,
    height: 11000,
    x: 500,
    y: 200,
    rx: 8000,
    ry: 7500,
  };

  // 绘制左侧切圆
  fourHuaYuan(options1, canvasEl1, cx1, cy1, 1);
  // 绘制右侧切圆
  fourHuaYuan(options2, canvasEl2, cx2, cy2, 2);
}

function setC(){
  let boxW = document.getElementById("eightJiaoBox").offsetWidth;
  // let boxW = 800;
  let boxH = (1080 * boxW) / 1920;

  jiaowidth.value = boxW;
  jiaoheight.value = boxH;
}

// 绘制椭圆的通用方法，最后一个参数用于区分左右（1=左，2=右）
function _fourHuaYuan(options, canvasElRef, cxRef, cyRef, index) {
  const container = canvasElRef.value.parentElement;
  // 设置canvas宽高（基于父容器，即单个circleLayer）
  canvasElRef.value.width = parseDimension(
    `${singleWidth.value}vw`,
    container.clientWidth
  );
  canvasElRef.value.height = parseDimension(
    `${jiaoheight.value}vh`,
    container.clientHeight
  );

  // 分别存储左右侧的宽高比例，避免相互影响
  if (index === 1) {
    widthC1.value = options.width / canvasElRef.value.width;
    heightC1.value = options.height / canvasElRef.value.height;
  } else {
    widthC2.value = options.width / canvasElRef.value.width;
    heightC2.value = options.height / canvasElRef.value.height;
  }

  const ctx = canvasElRef.value.getContext("2d");
  const a = options.rx / (index === 1 ? widthC1.value : widthC2.value);
  const b = options.rx / (index === 1 ? heightC1.value : heightC2.value);

  // 计算圆心坐标（基于各自的canvas）
  cxRef.value =
    options.x / (index === 1 ? widthC1.value : widthC2.value) +
    canvasElRef.value.width / 2;
  cyRef.value =
    options.y / (index === 1 ? heightC1.value : heightC2.value) +
    canvasElRef.value.height / 2;
  console.log(`第${index}个圆坐标: ${cxRef.value}, ${cyRef.value}`);

  // 设置椭圆样式（左右侧用不同颜色区分）
  ctx.lineWidth = 2;
  ctx.strokeStyle = "#6A95FF";

  // 绘制椭圆
  function drawEllipse(ctx, x, y, radiusX, radiusY) {
    ctx.beginPath();
    ctx.ellipse(x, y, radiusX / 2, radiusY / 2, 0, 0, Math.PI * 2);
    ctx.stroke();
  }

  drawEllipse(ctx, cxRef.value, cyRef.value, a, b);
}

// 解析尺寸的工具函数
const parseDimension = (value, max) => {
  if (value.endsWith("vw")) {
    return (parseFloat(value) / 100) * window.innerWidth;
  } else if (value.endsWith("vh")) {
    return (parseFloat(value) / 100) * window.innerHeight;
  } else if (value.endsWith("px")) {
    return parseFloat(value);
  }
  return max;
};
onUnmounted(() => {
  if (canvasEl1.value) {
    const ctx = canvasEl1.value.getContext("2d");
    ctx.clearRect(0, 0, canvasEl1.value.width, canvasEl1.value.height);
    // 释放资源
    canvasEl1.value = null;
  }
  if (canvasEl2.value) {
    const ctx2 = canvasEl2.value.getContext("2d");
    ctx2.clearRect(0, 0, canvasEl2.value.width, canvasEl2.value.height);
    // 释放资源
    canvasEl2.value = null;
  }
});
const clearImgSrc = () =>{
  pegSrc.value = "";
  pegSrc.value = import.meta.env.VITE_APP_BASE_API + `api/video/stream.mjpeg?timestamp=${Date.now()}`
}
watch(() =>route.path,(oldVal,newVal) =>{
  if(oldVal){
    clearImgSrc()
  }
})
defineExpose({clearImgSrc})
</script>

<style lang="scss" scoped>
.all-height-width {
  width: 100%;
  height: 100%;
}
.fourJiao {
  position: relative;
  display: inline-block;

  // 基础图片层样式
  .fourJiao4 {
    position: relative;
    background-color: transparent;
  }

  // 左右布局容器
  .circleLayersContainer {
    position: absolute;
    top: 0;
    left: 0;
    display: flex; // 启用flex布局实现左右排列
    gap: 0; // 左右div之间的间距（可根据需要调整）
    background-color: transparent;
    justify-content: space-between;
  }

  // 单个切圆信息div（左右各一个）
  .circleLayer {
    flex-shrink: 0;
    position: relative;
    background-color: transparent;
    width: 50%;
    height: 100%;
  }

  // 边框样式
  .fourJiao1 {
    position: relative;
    top: 0;
    left: 0;
    height: 100%;
    width: 100%;
    box-sizing: border-box; // 确保边框不影响宽高计算
  }

  // canvas样式（用于绘制椭圆）
  .fourJiao2 {
    position: absolute;
    top: 0;
    left: 0;
    height: 100%;
    width: 100%;
    background-color: transparent;
  }

  // 红色/蓝色"+"号样式
  .fourJiao3 {
    position: absolute;
    top: 0;
    left: 0;
    height: 100%;
    width: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
    background-color: transparent;
  }

  // 椭圆中心"+"号样式
  .clCenter {
    color: #6affb2;
    display: inline-block;
    position: absolute;
    transform: translate(-50%, -50%);
  }
}
</style>
<style>
.event-none{
  pointer-events: none;
}
</style>